package com.zzyl.nursing.service.impl;

import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.lang.hash.Hash;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zzyl.common.core.domain.R;
import com.zzyl.common.core.domain.model.LoginUser;
import com.zzyl.framework.web.service.TokenService;
import com.zzyl.nursing.domain.*;
import com.zzyl.nursing.dto.DeviceDto;
import com.zzyl.nursing.dto.ElderFamilyDto;
import com.zzyl.nursing.dto.MemberAddDto;
import com.zzyl.nursing.dto.UserLoginRequestDto;
import com.zzyl.nursing.mapper.*;
import com.zzyl.nursing.service.IFamilyMemberService;
import com.zzyl.nursing.service.WechatService;
import com.zzyl.nursing.vo.DeviceDataVo;
import com.zzyl.nursing.vo.LoginVo;
import com.zzyl.nursing.vo.MamberElderVo;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 老人家属Service业务层处理
 *
 * @author alexis
 * @date 2025-01-09
 */
@Service
public class FamilyMemberServiceImpl extends ServiceImpl<FamilyMemberMapper, FamilyMember> implements IFamilyMemberService {
    @Autowired
    private FamilyMemberMapper familyMemberMapper;

    @Autowired
    private WechatService wechatService;

    @Autowired
    private TokenService tokenService;




    static List<String> DEFAULT_NICKNAME_PREFIX = ListUtil.of(
            "生活更美好",
            "大桔大利",
            "日富一日",
            "好柿开花",
            "柿柿如意",
            "一椰暴富",
            "大柚所为",
            "杨梅吐气",
            "天生荔枝"
    );
    @Autowired
    private ElderMapper elderMapper;
    @Autowired
    private RoomMapper roomMapper;
    @Autowired
    private BedMapper bedMapper;
    @Autowired
    private DeviceMapper deviceMapper;
    @Autowired
    private DeviceDataMapper deviceDataMapper;

    /**
     * 查询老人家属
     *
     * @param id 老人家属主键
     * @return 老人家属
     */
    @Override
    public FamilyMember selectFamilyMemberById(Long id) {
        return familyMemberMapper.selectById(id);
    }

    /**
     * 查询老人家属列表
     *
     * @param familyMember 老人家属
     * @return 老人家属
     */
    @Override
    public List<FamilyMember> selectFamilyMemberList(FamilyMember familyMember) {
        return familyMemberMapper.selectFamilyMemberList(familyMember);
    }

    /**
     * 新增老人家属
     *
     * @param familyMember 老人家属
     * @return 结果
     */
    @Override
    public int insertFamilyMember(FamilyMember familyMember) {
        return familyMemberMapper.insert(familyMember);
    }

    /**
     * 修改老人家属
     *
     * @param familyMember 老人家属
     * @return 结果
     */
    @Override
    public int updateFamilyMember(FamilyMember familyMember) {
        return familyMemberMapper.updateById(familyMember);
    }

    /**
     * 批量删除老人家属
     *
     * @param ids 需要删除的老人家属主键
     * @return 结果
     */
    @Override
    public int deleteFamilyMemberByIds(Long[] ids) {
        return familyMemberMapper.deleteBatchIds(Arrays.asList(ids));
    }

    /**
     * 删除老人家属信息
     *
     * @param id 老人家属主键
     * @return 结果
     */
    @Override
    public int deleteFamilyMemberById(Long id) {
        return familyMemberMapper.deleteById(id);
    }

    /**
     * 小程序登录方法
     *
     * @param userLoginRequestDto 请求数据
     * @return 登录结果，包含token和nickname
     */
    @Override
    public LoginVo login(UserLoginRequestDto userLoginRequestDto) {
        // 1.调用微信官方接口获取openId
        String openId = wechatService.getOpenId(userLoginRequestDto.getCode());

        // 2.根据openId查询数据库获取用户信息
        FamilyMember familyMember = getOne(Wrappers.<FamilyMember>lambdaQuery().eq(FamilyMember::getOpenId, openId));

        // 3.如果用户信息不存在，就创建一个用户，并绑定openId
        if (ObjectUtils.isEmpty(familyMember)) {
            // 新用户
            familyMember = new FamilyMember();
            familyMember.setOpenId(openId);
        }

        // 4.调用微信接口获取手机号
        String phoneNumber = wechatService.getPhoneNumber(userLoginRequestDto.getPhoneCode());
        // 不论是新用户还是老用户，都更新手机号
        familyMember.setPhone(phoneNumber);

        // 5.保存或更新用户，如果是新增，要生成一个用户名
        saveOrUpdateFamilyMember(familyMember);

        // 6.封装用户信息到token中，返回给小程序
        LoginVo loginVo = new LoginVo();
        Map<String, Object> claims = new HashMap<>();
        claims.put("userId", familyMember.getId());
        claims.put("nickName", familyMember.getName());

        String token = tokenService.createToken(claims);
        loginVo.setToken(token);
        loginVo.setNickName(familyMember.getName());

        // 返回结果
        return loginVo;
    }

    /**
     * 分页查看已绑定家人列表
     * @param authorization
     * @param pageNum
     * @param pageSize
     * @return
     */
    @Override
    public List<MamberElderVo> listElder(String authorization, Integer pageNum, Integer pageSize) {
        // 构建返回参数
        List<MamberElderVo> mamberElderVos = new ArrayList<>();
        // 获取用户id
        Claims claims = tokenService.parseToken(authorization);
        Long userId = MapUtil.getLong(claims, "userId");
        // 根据用户id查询remark
        FamilyMember familyMember = familyMemberMapper.selectById(userId);
        String remark = familyMember.getRemark();
        List remarks = (List)JSON.parseArray(remark);
        for (Object item : remarks) {
            String elderId = JSON.parseObject(item.toString()).get("elderId").toString();
            // 构建老人信息
            MamberElderVo mamberElderVo = new MamberElderVo();
            mamberElderVo.setMid(String.valueOf(userId));
            mamberElderVo.setMremark(JSON.parseObject(item.toString()).get("remark").toString());
            mamberElderVo.setElderId(elderId);
            // 获取老人信息
            Elder elder = elderMapper.selectElderById(Long.valueOf(elderId));
            mamberElderVo.setName(elder.getName());
            //老人头像
            String image = elder.getImage();
            mamberElderVo.setImage(image);
            mamberElderVo.setBedNumber(elder.getBedNumber());
            // 获取老人房间信息
            Bed bed = bedMapper.selectBedById(elder.getBedId());
            Room room = roomMapper.selectRoomById(bed.getRoomId());
            mamberElderVo.setTypeName(room.getTypeName());
            // 获取老人设备信息
            Device device = deviceMapper.selectbyBandingLocation(String.valueOf(elder.getId()));
            if (!ObjectUtils.isEmpty(device)) {
                mamberElderVo.setIotId(device.getIotId());
                mamberElderVo.setDeviceName(device.getDeviceName());
                mamberElderVo.setProductKey(device.getProductKey());
            }
            mamberElderVos.add(mamberElderVo);
        }

        return mamberElderVos;
    }

    /**
     * 绑定家属
     *
     * @param memberAddDto
     * @return
     */
    @Override
    public R addRemark(MemberAddDto memberAddDto, String authorization) {
        // 获取当前登录用户
        Claims claims = tokenService.parseToken(authorization);
        Long userId = MapUtil.getLong(claims, "userId");
        //1. 根据身份证号查询老人信息
        String idCard = memberAddDto.getIdCard();
        Elder elder = elderMapper.selectElderByIdCard(idCard);
        //2. 判断是否存在
        if (ObjectUtil.isEmpty(elder)) {
            // 不存在
            //throw new RuntimeException("该老人不存在");
            return R.fail("老人不存在");
        }
        // 如果老人存在 保存老人id和称呼到用户的remark
        List<Map> remarks = new ArrayList<>();
        String remark = familyMemberMapper.selectFamilyMemberById(userId).getRemark();
        if (!"".equals(remark) && !StringUtils.isEmpty(remark)) {
            remarks = (List)JSON.parseArray(remark);
        }

        HashMap<String, Object> oneRemark = new HashMap<>();
        oneRemark.put("elderId", elder.getId());
        oneRemark.put("remark", memberAddDto.getRemark());
        remarks.add(oneRemark);
        String jsonString = JSON.toJSONString(remarks);
        FamilyMember familyMember = new FamilyMember();
        familyMember.setId(userId);
        familyMember.setRemark(jsonString);
         //更新家庭成员的备注信息
        familyMemberMapper.updateRemarkById(familyMember);
        return R.ok("添加成功");
    }

    /**
     * 新增或更新老人家属
     *
     * @param familyMember 老人家属对象
     */
    private void saveOrUpdateFamilyMember(FamilyMember familyMember) {
        // 判断id是否为空
        if (ObjectUtils.isEmpty(familyMember.getId())) {
            // 新增
            // 生成一个随机的用户名，规则是：一个随机的好听的名字+手机号后4位
            String prefix = DEFAULT_NICKNAME_PREFIX.get((int) (Math.random() * DEFAULT_NICKNAME_PREFIX.size()));
            String nickName = prefix + familyMember.getPhone().substring(7);
            familyMember.setName(nickName);
            familyMemberMapper.insert(familyMember);
        } else {
            // 更新
            familyMemberMapper.updateById(familyMember);
        }
    }

    /**
     * 查询健康数据
     * @param authorization
     * @param deviceDto
     * @return
     */
    @Override
    public Map queryDevicePropertyStatus(String authorization, DeviceDto deviceDto) {
        List<DeviceDataVo> deviceDataVos = new ArrayList<>();
        // 查询设备的参数信息
        List<DeviceData> deviceDatas = deviceDataMapper.selectbyProductKey(deviceDto.getProductKey());
        // 组装数据
        for (DeviceData deviceData : deviceDatas) {
            DeviceDataVo deviceDataVo = new DeviceDataVo();
            deviceDataVo.setDataType("int");
            deviceDataVo.setIdentifier(deviceData.getFunctionId());
            deviceDataVo.setName(deviceData.getRemark());
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            try {
                Date date = simpleDateFormat.parse(deviceData.getAlarmTime().toString().replace("T", " "));
                deviceDataVo.setTime(String.valueOf(date.getTime()));
            } catch (ParseException e) {
                e.printStackTrace();
            }
            deviceDataVo.setUnit(null);
            deviceDataVo.setValue(deviceData.getDataValue());
            deviceDataVos.add(deviceDataVo);
        }
        Map<String, Object> data = new HashMap<>();
        data.put("propertyStatusInfo", deviceDataVos);
        HashMap<Object, Object> objectObjectHashMap = new HashMap<>();
        objectObjectHashMap.put("list", data);
        return objectObjectHashMap;
    }
}
